﻿

Type PIDController
Private : 
    kp_ As Double               '//比例增益 
    ki_ As Double               '//积分增益 
    kd_ As Double               '//微分增益         
    integral_ As Double = 0.0   '// 积分项累计值    
    lastError_ As Double = 0.0  '// 上一个误差    
    setPoint_ As Double         '// 设定点      
Public:        
    Declare Constructor(ByVal kp As Double, ByVal ki As Double, ByVal kd As Double, ByVal setPoint As Double)   
    Declare Function Calculate(ByVal currentValue As Double) As Double 
    Declare Sub setSetPoint(ByVal setPoint As Double)      
End Type

Constructor PIDController(ByVal kp As Double,ByVal ki As Double,ByVal kd As Double, ByVal setPoint As Double)
    kp_ = kp
    ki_ = ki
    kd_ = kd
    setPoint_ = setPoint
End Constructor
 
Function PIDController.Calculate(ByVal currentValue As Double) As Double 
    Dim dError As Double = setPoint_ - currentValue         '// 计算误差 
    integral_ += dError                                     '// 累积误差
    Dim derivative As Double = dError - lastError_          '// 计算微分项 
    lastError_ = dError
    Return Kp_ * dError + Ki_ * integral_ + Kd_ * derivative  '// 计算控制量
End Function

Sub PIDController.setSetPoint(ByVal setPoint As Double)
    setPoint_ = setPoint
End Sub

 








'Type PIDController
'Private:
'    kp_ As Double
'    ki_ As Double
'    kd_ As Double
'    integral_ As Double = 0.0
'    previous_error_ As Double = 0.0
'Public:    
'    Declare Constructor(ByVal kp As Double,ByVal ki As Double,ByVal kd As Double)
'    Declare Function compute(ByVal setpoint As Double,ByVal feedback As Double,ByVal dt As Double) As Double    
'End Type
'
'Constructor PIDController(ByVal kp As Double,ByVal ki As Double,ByVal kd As Double)
'    kp_ = kp
'    ki_ = ki
'    kd_ = kd
'End Constructor
'
''/**
''* @brief 计算PID控制器的输出
''* @param setpoint 设定值
''* @param feedback 反馈值
''* @param dt 时间间隔
''* @Return
''*/
'Function PIDController.Compute(ByVal setpoint As Double, ByVal feedback As Double, ByVal dt As Double) As Double   
'    Dim derr As Double = setpoint - feedback '// 误差,比例项使得控制系统能够迅速响应并逼近设定值
'    integral_ += derr * dt                   '// 累积误差,积分项用于补偿系统的稳态误差,即长时间内无法通过比例项和微分项完全纠正的误差
'    Dim derivative As Double = (derr - previous_error_) / dt '// 误差的导数,微分项帮助控制系统更快地响应变化,并减小超调和震荡
'    Dim outp As Double = kp_ * derr + ki_ * integral_ + kd_ * derivative '// 控制量计算 
'    previous_error_ = derr
'    Return outp
'End Function






